package com.ita.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DBUtil {

	// private static final String DRIVER_NAME = "oracle.jdbc.OracleDriver";
	private static final String DRIVER_NAME = "oracle.jdbc.driver.OracleDriver";
	private static final String URL = "jdbc:oracle:thin:@zha-ita105-w7:1521:orcl";
	private static final String USER_NAME = "bryce";
	private static final String PASSWORD = "123";

	// private static final String DRIVER_NAME = "DRIVER_NAME";
	// private static final String URL = "URL";
	// private static final String USER_NAME = "USER_NAME";
	// private static final String PASSWORD = "PASSWORD";
	// private static final Map<String, String> config = new HashMap<String,
	// String>();

	private static DataSource jndiDs;
	private static DataSource ds;
	private static Logger logger = Logger.getLogger(DBUtil.class);

	public static Connection createConnection() {

		Connection conn = null;
		try {
			Class.forName(DRIVER_NAME);
			conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
			// Class.forName(config.get(DRIVER_NAME));
			// conn = DriverManager.getConnection(config.get(URL),
			// config.get(USER_NAME), config.get(PASSWORD));
		} catch (ClassNotFoundException e) {
			logger.error(e.getMessage());
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}

		return conn;
	}

	public static Connection createByDs() {

		Connection conn = null;
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
		return conn;
	}

	public static Connection createByJNDI() {

		Connection conn = null;

		try {
			Context cxt = new InitialContext();
			jndiDs = (DataSource) cxt.lookup("java:/comp/env/jdbc/myoracle");
			return jndiDs.getConnection();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return conn;
	}

	public static void close(Connection conn, PreparedStatement pst, ResultSet rSet) {

		try {
			if (conn != null) {
				conn.close();
			}
			if (pst != null) {
				pst.close();
			}
			if (rSet != null) {
				rSet.close();
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

	public void open() {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		ds = (BasicDataSource) context.getBean("dataSource");
	}

	public static void main(String[] args) {
		Connection conn = DBUtil.createByDs();
		System.out.println(conn);
	}

	public static void setDs(DataSource ds) {
		DBUtil.ds = ds;
	}
}
